<?php

namespace Account\Controller;

use Common\Controller\ApiController;
use Firebase\JWT\JWT;
use Common\Model\ModelException;
use Transform\UserTransform;
use Ruben\Tcyun\TcIM;
use Ruben\Yxyun\Yxim;
use Util\StringUtils;
use Util\ModelUtils;
use Util\Curl;

class UserController extends ApiController {

    /**
     * 临时登录
     *
     * @return void
     */
    public function loginByTemporary() {
        $user = [
            'user_id' => 0,
            'account' => StringUtils::keyGen(),
        ];

        $user = transform('User', 'token', $user);
        $token = JWT::encode($user, C('AUTH_KEY'));
        $ret = ['access_token' => $token, 'expired_at' => $user['exp']];
        $this->response($ret);
    }

    public function register()  {
        $input = $this->request();
        $mobile = $input['mobile'];
//        $mobileCode = $input['mobile_code'];
        $password = $input['password'];
        $sk = isset($input['sk']) ? $input['sk'] : ''; //邀请码
        if (empty($password) || empty($mobile)) {
            $this->errorResponse(110019);
        }

        $userModel = D('Users');
        try {
            $user = $userModel->register($mobile, $password, $mobile, 'https://jinbanbook.oss-cn-shenzhen.aliyuncs.com/default.png', 1, $sk);
            $user = transform('User', 'details', $user);
            $token = JWT::encode($user, C('AUTH_KEY'));
            $ret = ['access_token' => $token, 'expired_at' => $user['exp']];
            $this->response($ret);
            $this->createdResponse();
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    public function loginByMobile() {
        $input = $this->request();
        $mobile = $input['mobile'];
        $password = filter($input['password'], null);
        $mobileCode = filter($input['mobile_code'], null);

        if (!empty($mobileCode)) {
            /* 验证手机验证码 */
            if (!$this->checkMobileCode($mobile, $mobileCode)) {
                $this->errorResponse(10009);
            }
        }

        $userModel = D('Users');
        try {
            $user = $userModel->loginByMobile($mobile, $password, $mobileCode);
            if (C('im.open') == 1 && empty($user['token'])) {
                $yx_token = $this->getImId($user['user_id']);
                $user = array_merge($user, $yx_token);
            }
            $token = transform('User', 'token', $user);
            $userinfo = transform('User', 'details', $user);
            $token = JWT::encode($token, C('AUTH_KEY'));
            $ret = ['access_token' => $token, 'user' => $userinfo, 'expired_at' => $user['exp']];
            $this->response($ret);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    private function getPeriods($uid) {
        $periods = D('UserPeriod')->getByUserId($uid);
        if (!$periods) {
            $periods = [];
        }
        return $periods;
    }

    /**
     * 社会登录
     *
     * @return void
     */
    public function loginBySocial() {
        $input = $this->request();

        $this->checkNull($input, ['openid', 'unionid', 'avatar', 'nickname', 'sex']);
        $userModel = D('Users');
        try {
            $user = $userModel->socialLogin($input['openid'], $input['nickname'], $input['avatar'], $input['sex'], $input['unionid']);
            $token = transform('User', 'token', $user);
            $userinfo = transform('User', 'details', $user);
            $token = JWT::encode($token, C('AUTH_KEY'));
            $ret = ['access_token' => $token, 'user' => $userinfo, 'expired_at' => $user['exp']];
            $ret['user']['periods'] = $this->getPeriods($user['user_id']);
            $ret['user']['msg_num'] = $this->msgbok($user['user_id']); //暂时没做
            $this->response($ret);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 更新token时间
     */

    public function refreshToken() {
        $user = $this->user;
        $input = $this->request();
        if (!empty($user['id']))
            D('Users')->saveLoginLog($user['user_id']);
        $user['iat'] = time();
        $user['exp'] = time() + 3600 * 24 * 7;
        $token = JWT::encode($user, C('AUTH_KEY'));
        $ret = ['access_token' => $token, 'expired_at' => $user['exp']];
        $this->response($ret);
    }

    /*
     * 绑定手机号
     */

    public function bindMobile() {
        $user = $this->user;
        $input = $this->request();
        $mobile = $input['mobile'];
        $mobileCode = $input['mobile_code'];
        if ($this->checkMobileCode($mobile, $mobileCode)) {
            try {
                D('Users')->bindMobile($user['id'], $mobile);
                $this->modifySuccessResponse();
            } catch (ModelException $e) {
                $this->errorModelResponse($e);
            }
        } else {
            $this->errorResponse(10009);
        }
    }

    public function bindSocial() {
        $input = $this->request();
        $this->checkNull($input, ['openid', 'source', 'avatar', 'nickname', 'sex', 'unionid']);

        $userModel = D('Users');
        try {
            $user = $userModel->socialLogin($input['source'], $input['openid'], $input['nickname'], $input['avatar'], $input['sex'], $input['unionid'] = '');
            $this->createdResponse();
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*     * 书城没有用到* */

    public function resetPassword() {
        $input = $this->request();
        $oldPassword = $input['old_password'];
        $newPassword = $input['new_password'];
        if ($newPassword === '')
            $this->errorResponse(30000, '密码不能为空');
        $userModel = D('Users');
        $user = $userModel->find($this->user['id']);
        if ($user) {
            if (empty($user['password']) || md5($oldPassword) === $user['password']) {
                $user['password'] = md5($newPassword);
                $userModel->save($user);
                $user = $userModel->login($user);
                try {
                    $user = transform('User', 'details', $user);
                    $this->response($user);
                } catch (ModelException $e) {
                    $this->errorModelResponse($e);
                }
            } else {
                $this->errorResponse(30003, '密码错误');
            }
        } else {
            $this->errorResponse(30001, '该手机未注册');
        }
    }

    public function update() {
        $uid = $this->user['id'];
        $input = $this->request();
        $userModel = D('Users');
        if ($input['nickname'] && mb_strlen($input['nickname']) < 2) {
            $this->errorResponse(30000, '昵称最少2个字');
        }
        if (D('Users')->where(['mobile' => $input['mobile']])->find()) {
            $this->errorResponse(30000, '手机号已存在');
        }
        try {
            if (count($input) > 0) {
                $userModel->updateInfo($uid, $input);
            }
            $user = D('Users')->find($uid);
            $user['empty_password'] = $user['password'] ? 0 : 1;
            $user['pay_password'] = $user['pay_password'] ? 1 : 0;
            $user = transform('User', 'details', $user);
            $this->response($user);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /**
     * 获取个人信息
     */
    public function getInfo() {
        $input = $this->request();
//        $uid = filter($input['uid'], null);
        $mobile = filter($input['mobile'], null);
        $fields = $input['fields'];
        $scope = filter($input['scope'], 'details');
//        $uid = $uid ? $uid : $this->user['id'];
        $uid = $this->user['id'];
        if ($mobile) {
            $user = D('Users')->where(['mobile' => $mobile])->find(); //通过手机号搜索用户
            if(empty($user)){
                $this->errorResponse('100002','搜索的用户不存在');
            }
        } else {
            $user = D('Users')->find($uid);
        }
        //当前用户和搜索用户的关系
        if ($user['user_id'] != $this->user['id']) {
            if (C('im.open') == 1) {
                $user['relation'] = 0;
                $imConfig = C('sdk.yxim');
                $yxim = new Yxim($imConfig);
                $result = $yxim->getFriend($this->user['id']);
                $faccids = array_column($result['friends'], 'faccid');
                if (in_array($user['user_id'], $faccids)) {
                    $user['relation'] = 1; //好友
                }
            }
        } else {
            $user['empty_password'] = $user['password'] ? 0 : 1;
            $user['pay_password'] = $user['pay_password'] ? 1 : 0;
        }
        $user = transform('User', $scope, $user);

        $UserFriends = D('UserFriends');
        //查询被添加好友信息消息
        $user['req_add_friend_count'] = $UserFriends->where(['faccid' => $uid, 'type' => 2])->count();
        $this->response($user);
    }

    /*     * 浏览历史* */

    public function bookHistory() {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $user = $this->user;
        $uid = $user['id'];
        $users[] = $uid;
        $temp_uid = $uid;
        if (!empty($input['temp_uid'])) {
            $temp_uid = $input['temp_uid'];
            $users[] = $input['temp_uid'];
        }
        $historyModel = D('History');
        $sql = "SELECT count(id) as count FROM (SELECT id  FROM `n_history` WHERE `uid` in ({$uid},{$temp_uid}) AND `del_time` = 0 GROUP BY biid) a LIMIT 1";
        $count = $historyModel->query($sql);

        if (count($count) > 0) {
            $count = $count[0]['count'];
            $history = $historyModel
                    ->table('__HISTORY__ as h')
                    ->join('__BOOK__ as b on h.biid = b.id')
                    ->field('b.id,b.title,b.img,b.author,h.chapter_id,h.time')
                    ->group('h.biid')
                    ->where(['h.uid' => ['in', $users], 'h.del_time' => 0])
                    ->page($page, $perPage)
                    ->order('h.time desc')
                    ->select();
            if (!empty($history)) {
                $b_ids = array_column($history, 'id');
                $history_shelves = D('Bookshelves')->where(['user_id' => ['in', $users], 'b_id' => ['in', $b_ids], 'del_time' => 0])->getField('b_id', true);
                foreach ($history as $key => $value) {
                    if (empty($history_shelves)) {
                        $history[$key]['shelves'] = 0;
                    } else {
                        if (in_array($history[$key]['id'], $history_shelves)) {
                            $history[$key]['shelves'] = 1;
                        } else {
                            $history[$key]['shelves'] = 0;
                        }
                    }
                }
            }
        }

        $pagination = pagination($count, $perPage, $page);
        $this->response($history, $pagination);
    }

    /*     * 删除浏览书历史* */

    public function delBookHistory() {
        $user = $this->user;
        $input = $this->request();
        $uid = $user['id'];
        $users[] = $uid;
        if (!empty($input['temp_uid'])) {
            $users[] = $input['temp_uid'];
        }
        D('History')->where(['uid' => ['in', $users]])->setField(['del_time' => time()]);
        $this->asyncResponse();
    }

    public function getPaymentLogs() {
        $user = $this->user;
        $GoldLog = M('GoldLog');
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $type = filter($input['type'], 'cost');
        $where = ['g.user_id' => $user['id'], 'g.type' => $type];
        $count = $GoldLog->table('__GOLD_LOG__ as g')->field('g.id')->where($where)->count();
        $logs = $GoldLog
                ->table('__GOLD_LOG__ as g')
                ->join('__BOOK__ as b ON b.id = g.bid')
                ->field('b.title,g.mark,g.gold,g.add_time')
                ->where($where)
                ->page($page, $perPage)
                ->order('g.add_time desc')
                ->select();
//        $logs = transform('PaymentLog', 'listview', $logs);
        $pagination = pagination($count, $perPage, $page);
        $this->response($logs, $pagination);
    }

    public function getChargeLogs() {
        $user = $this->user;
        $GoldLog = M('GoldLog');
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $type = filter($input['type'], 'charge');
        $where = ['user_id' => $user['id'], 'type' => $type];
        if (in_array($type, ['send', 'cost', 'charge'])) {
            $where['gold'] = ['gt', 0];
        }
        $count = $GoldLog->field('id')->where($where)->count();
        $logs = $GoldLog
                ->field('mark,gold,add_time')
                ->where($where)
                ->page($page, $perPage)
                ->order('add_time desc')
                ->select();
//        $logs = transform('PaymentLog', 'listview', $logs);
        $pagination = pagination($count, $perPage, $page);
        $this->response($logs, $pagination);
    }

    public function forgotPasswd() {
        $input = $this->request();
        $this->checkNull($input, ['mobile', 'new_password']);

        $usersModel = D('Users');
        try {
            $user = $usersModel->updatePwd($input['mobile'], $input['new_password']);
            $this->createdResponse();
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /**
     * 用户提现申请
     */
    public function withdrawMoney() {
        $user = $this->user;
        $input = $this->request();
        // 单位转换 
        $amount = filter($input['amount'], 0);
        if ($amount < 1)
            $this->errorResponse(30024);
        $amount *= 100;
        $bankcard = D('BankCard')->find($input['id']);
        if (empty($bankcard))
            $this->errorResponse(30017);
        try {
            D('Users')->costMoney($user['id'], 'withdraw', $amount, '提现申请', 'money');
            M('Withdraw')->add([
                'user_id' => $user['id'],
                'amount' => $amount,
                'create_time' => time(),
                'status' => 'pending',
                'bank' => $bankcard['bank'],
                'cardholder' => $bankcard['cardholder'],
                'mobile' => $bankcard['mobile'],
                'sub_branch' => $bankcard['sub_branch'],
                'account' => $bankcard['account'],
            ]);

            $this->createdResponse(['cdoe' => 200, 'message' => '提现申请成功，后台正在审核']);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 提现记录
     */

    public function getWithdraws() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = [];
        $where['user_id'] = $user['id'];
        $count = D('Withdraw')->where($where)->count();
        $logs = D('Withdraw')
                ->where($where)
                ->order('create_time desc')
                ->page($page, $perPage)
                ->select();
        $logs = $logs ? : [];
        $logs = transform('Withdraw', 'listview', $logs);
        $pagination = pagination($count, $perPage, $page);
        $this->response($logs, $pagination);
    }

    public function getScoreHistory() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = [];
        $where['to_uid'] = $user['id'];
        $count = D('ScoreLog')->where($where)->count();
        $logs = D('ScoreLog')
                ->where($where)
                ->page($page, $perPage)
                ->order('create_time desc')
                ->select();
        $logs = transform('ScoreLog', 'listview', $logs);
        $pagination = pagination($count, $perPage, $page);
        $this->response($logs, $pagination);
    }

    public function getMoneyLogs() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = [];
        $where['user_id'] = $user['id'];
        if ($input['type']) {
            if (strpos($input['type'], ',') !== false) {
                $where['type'] = ['in', explode(',', $input['type'])];
            } else {
                $where['type'] = $input['type'];
            }
        }
        $count = D('CashLog')->where($where)->count();
        $logs = D('CashLog')->where($where)
                ->page($page, $perPage)
                ->order('create_time desc')
                ->select();
        $logs = transform('CashLog', 'listview', $logs);
        $pagination = pagination($count, $perPage, $page);
        $this->response($logs, $pagination);
    }

    public function getAnchor($id) {
        $where = [
            'role' => 3,
            'user_id' => $id,
        ];
        $user = D('Users')->where($where)->find();
        if (empty($user))
            $this->errorResponse(10000);
        ModelUtils::manyToMany($user, ['User.user_id', 'AnchorTags.user_id', 'LiveTag.id', 'AnchorTags.tag_id'], 'tags');
        $user = transform('User', 'anchor', $user);
        $this->response($user);
    }

    public function searchAnchors() {
        $input = $this->request();
        $tagids = $input['tag_id'];
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $keyword = filter($input['keyword'], '');

        $where = [];
        $where['role'] = 3;
        if ($tagids) {
            $ids = explode(',', $tagids);
            $uids = M('anchor_tags')->where(['tag_id' => ['in', $ids]])->getField('user_id', true);
            $where['user_id'] = empty($uids) ? -1 : ['in', $uids];
        }
        if ($keyword) {
            $where['nickname'] = ['like', "%{$keyword}%"];
        }
        $count = D('Users')->where($where)->count();
        $users = D('Users')->where($where)->order('followers_count desc')->page($page, $perPage)->select();

        ModelUtils::manyToMany($users, ['User.user_id', 'AnchorTags.user_id', 'LiveTag.id', 'AnchorTags.tag_id'], 'tags');
        // 补充标签
        $users = transform('User', 'anchor', $users);
        $pagination = pagination($count, $perPage, $page);
        $this->response($users, $pagination);
    }

    public function privateChatNotify($uid) {
        $input = $this->request();
        $user = $this->user;
        $this->checkNull($input, ['msg']);
        $from = D('Users')->find($user['id']);
        $to = D('Users')->find($uid);
        D('Helper/Notification')->privateChat($from, $to, $input['msg']);
        $this->modifySuccessResponse();
    }

    public function block() {
        $user = $this->user;
        $input = $this->request();
        $to = $input['to_user_id'];
        if ($user['id'] == $to)
            $this->errorResponse(30019);
        $exist = M('Blacklist')->where(['id' => $user['id'], 'to_user_id' => $to])->find();
        if ($exist)
            $this->errorResponse(30018);
        M('Blacklist')->add([
            'user_id' => $user['id'],
            'to_user_id' => $to,
            'create_time' => time(),
        ]);
        $this->createdResponse();
    }

    public function cancelBlock($to) {
        $user = $this->user;
        $where = ['user_id' => $user['id'], 'to_user_id' => $to];
        $toUser = M('Blacklist')->where($where)->find();
        if (empty($toUser))
            $this->errorResponse(10000);
        M('Blacklist')->delete($toUser['id']);
        $this->modifySuccessResponse();
    }

    public function getBlacklist() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = ['user_id' => $user['id']];
        $count = M('Blacklist')->where($where)->count();
        $toids = M('Blacklist')
                ->where(['id' => $user['id']])
                ->page($page, $perPage)
                ->order('create_time desc')
                ->getField('to_user_id', true);
        if ($toids) {
            $users = D('Account/User')
                    ->where(['id' => ['in', $toids]])
                    ->select();
            $users = transform('User', 'pub', $users);
        }
        $pagination = pagination($count, $perPage, $page);
        $this->response($toids ? $users : [], $pagination);
    }

    public function getIntegral() {
        $yimei_integral = D('Users')->where(['id' => $this->user['id']])->getField('yimei_integral');
        $proportion = D('IntegralProportion')->getField('integral_proportion');
        $data['integral'] = $yimei_integral;
        $data['proportion'] = $proportion;
        $this->response($data);
    }

    public function getCollected() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $count = M('goodsCollected')->where(['id' => $user['id']])->count();
        $collected = M('goodsCollected')->where(['id' => $user['id']])->page($page, $perPage)->select();
        if ($collected) {
            $goods_ids = array_column($collected, 'goods_id');
            $goods = D('Goods')->where(['goods_id' => ['in', $goods_ids], 'delete_time' => 0])->select();
            $filtergoods = array_column($goods, null, 'goods_id');

            foreach ($collected as &$col) {
                $filtergoods[$col['goods_id']]['photo'] = explode(",", $filtergoods[$col['goods_id']]['photo']);
                $col['goods'] = $filtergoods[$col['goods_id']];
                $col['photo'] = $filtergoods[$col['goods_id']]['photo'];
            }
        } else {
            $collected = [];
        }

        $pagination = pagination($count, $perPage, $page);
        $this->response($collected, $pagination);
    }

    /*
     * 邮箱绑定
     */

    public function email() {
        $uid = $this->user['id'];
        $input = $this->request();
        $email = $input['email'];

        //发送邮箱验证码
        if (isEmail($email)) {
//            if(S("email_lock_{$email}")==1){
//                $this->errorResponse(110023);
//            }else{
            $code = StringUtils::randString(6, 1);
            S("email_lock_{$email}", 1, 60);
            $expire = 7200;
            S("{$uid}_{$code}", $code, $expire);
//            }
            $result = D('Email')->sendMail($code, $email);
            if ($result) {
                $this->createdResponse();
            } else {
                $this->errorResponse('110024');
            }
        } else {
            $this->errorResponse('110025');
        }
    }

    public function bindEmail() {
        $input = $this->request();
        $uid = $this->user['id'];
        $email = $input['email'];
        $vcode = $input['email_code'];
        //确认绑定
        if (!empty($vcode) && !empty($email)) {
            if (S("{$uid}_{$vcode}") == $vcode) {
                D('Users')->setField([
                    'user_id' => $uid,
                    'email' => $email,
                ]);
                $this->createdResponse();
            } else {
                $this->errorResponse('110026');
            }
        } else {
            $this->errorResponse('110027');
        }
    }

    public function checkToken() {
        $input = $this->request();
        $json = $this->sessionkey($input['code']);
        $sessionKeyArr = json_decode($json, TRUE);
        S($sessionKeyArr['openid'], $sessionKeyArr['session_key'], $expire = 7200);
        $connect = D('Connect')->where(['open_id' => $sessionKeyArr['openid']])->find();
        if ($connect) {
            $user = D('Users')->find($connect['uid']);
            D('Users')->login($user);
            $user['im_sig'] = $this->getTcIM($user);
            $user = transform('User', 'token', $user);
            $token = JWT::encode($user, C('AUTH_KEY'));
            $ret = ['access_token' => $token, 'expired_at' => $user['exp'], 'sessionkey' => $sessionKeyArr['openid']];
            $this->response($ret);
        } else {
            $this->errorResponse('10013', $sessionKeyArr['openid']);
        }
    }

    public function getTcIM($user) {
        $tcimConfig = C('sdk.tcim');
        $tcim = new TcIM($tcimConfig);
        $im_sig = $tcim->genCmdSig($user['user_id']);
        return $im_sig;
    }

    private function sessionkey($param) {
        $weixin = C('sdk.weixin');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $weixin['appid'] . '&secret=' . $weixin['secret'] . '&js_code=' . $param . '&grant_type=authorization_code';
        $curl = new Curl();
        $json = $curl->get($url);  //{"session_key":"FX0zTxPJ9iDrxdqKqhXPag==","openid":"okmPD5Cr-7xKJ6fFB31FSkLYvomQ"}
        return $json;
    }

    public function keyfu() {
        $kufu['kefu'] = D('Kefu')->field('orderby', true)->order('orderby ASC')->select();
        $kufu['onlinetime'] = '周一至周六9：00-18：00';
        $kufu['weixun'] = 'xin202626';
        $this->response($kufu);
    }

    /*     * 反馈* */

    public function feedbook() {
        $input = $this->request();
        if (empty($input['content'])) {
            $this->errorResponse('10002', '提交内容不能为空');
        }
//        if (empty($input['mobile'])) {
//            $this->errorResponse('10002', '请留下联系方式');
//        }
//        if (empty($input['cate_id']) || empty($input['cate_name'])) {
//            $this->errorResponse('10002', '请选择分类');
//        }
        $uid = $this->user['id'];
        $data = [
            'content' => $input['content'],
            'mobile' => $input['mobile'],
            'cate_id' => $input['cate_id'],
            'cate_name' => $input['cate_name'],
            'user_id' => $uid,
            'create_ip' => get_client_ip(),
            'create_time' => time()
        ];
        if (D('Feedback')->create($data)) {
            D('Feedback')->add();
            $this->createdResponse();
        } else {
            $this->errorResponse(401, '提交失败，请重试');
        }
    }

    public function feedbookCate() {
        $data = D('Feedbook')->cate();
        $this->response($data);
    }

    /*
     * 手机验证码登入即注册
     */

    public function loginAndregisterByMobile() {
        $input = $this->request();
        $mobile = $input['mobile'];
        $mobileCode = filter($input['mobile_code']);
        $this->checkNull($input, ['mobile', 'mobile_code']);
        if (!empty($mobileCode)) {
            if (!$this->checkMobileCode($mobile, $mobileCode)) {
                $this->errorResponse(10009);
            }
        }

        $userModel = D('Users');
        try {
            $user = $userModel->loginAndRegister($mobile);
            if (C('im.open') == 1 && empty($user['token'])) {
                $yx_token = $this->getImId($user['user_id']);
                $user = array_merge($user, $yx_token);
            }

            $token = transform('User', 'token', $user);
            $userinfo = transform('User', 'details', $user);
            $token = JWT::encode($token, C('AUTH_KEY'));
            $ret = ['access_token' => $token, 'user' => $userinfo, 'expired_at' => $user['exp']];
            $this->response($ret);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 更新云信的接口id
     */

    public function refreshAccid() {
        $id = $this->user['id'];
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        $yxim->updateUserId($id);
        $this->createdResponse();
    }

    /*
     * 更新云信的token
     */

    public function refreshTokenYxIM() {
        $id = $this->user['id'];
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        $result = $yxim->updateUserToken($id);
        $data['token'] = $result['info']['token'];
        $this->response($data);
    }

    /*
     * 添加好友
     * accid  一般是当前用户id
     * faccid  加好友接收者accid 
     * type  1直接加好友，2请求加好友，3同意加好友，4拒绝加好友
     * msg
     * serverex
     */

    public function addFriends() {
        $input = $this->request();
        $this->checkNull($input, ['faccid', 'type']);
        $id = $this->user['id'];
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        $result = $yxim->addFriend($id, $input['faccid'], $input['type'], $input['msg']);
        if ($result['code'] == 200) {
            $input['accid'] = $id;
            $input['add_time'] = time();
            D('UserFriends')->add($input);
        }
        //同意添加好友后，给对方发送一条消息

        if ($input['type'] == 3) {
            $yxim->sendMsg($id, 0, $input['faccid'], 0, ['msg' => '你们已经是好友了，现在可以聊天了']);
        }

        $this->createdResponse();
    }

    /*
     * 更新云信好友信息(给好友加备注)
     */

    public function updateFriend() {
        $input = $this->request();
        $id = $this->user['id'];
        $where['accid'] = $id;
        $where['faccid'] = $input['faccid'];
        $data['alias'] = $input['alias'];
        $data['mobile'] = $input['mobile'];
        $data['ext'] = $input['ext'];
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        if (!empty($input['alias'])) {
            $yxim->updateFriend($id, $input['faccid'], $data['alias']);
        }
        $where['delete_time'] = 0;
        D('UserFriends')->where($where)->setField($data);
        $friend = D('UserFriends')->field('alias,mobile,ext')->where($where)->find();
        $this->response($friend);
    }

    /*
     * 删除好友
     */

    public function delFriend() {
        $input = $this->request();
        $id = $this->user['id'];
        $where['accid'] = $id;
        $where['faccid'] = $input['faccid'];
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        $result = $yxim->deleteFriend($id, $input['faccid']);
        if ($result['code'] == 200) {
            D('UserFriends')->where($where)->setField('delete_time', time());
        }
        $this->createdResponse();
    }

    /*
     * 好友列表
     */

    public function getFriends() {
        $id = $this->user['id'];
        $input = $this->request();
        $page = filter($input['page'], 1);
        $relation_type = filter($input['relation_type'], 0); //	1黑名单，2静音，0正常
        $perPage = filter($input['per_page'], 100);
        $userM = D('Users');
        //从云信获取好友先
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        if ($relation_type == 1) {
            $friends = $yxim->listBlackFriend($this->user['id']);
            $blacklist = $friends['blacklist'];
            if (count($blacklist) > 0) {
                $faccids = $blacklist;
            }
        } else {
            $friends = $yxim->getFriend($this->user['id']);
            if (count($friends['friends']) > 0) {
                $faccids = array_column($friends['friends'], 'faccid');
                //去掉黑名单中的
                $listBlackFriend = $yxim->listBlackFriend($this->user['id']);
                $blacklist = $listBlackFriend['blacklist'];
                $faccids = array_diff($faccids, $blacklist);
            }
        }
        $users = [];
        if (count($faccids) > 0) {
            $count = $userM->where(['user_id' => ['in', $faccids]])->count();
        }
        if ($count > 0) {
            $users = $userM
                    ->where(['user_id' => ['in', $faccids], 'closed' => 0])
                    ->page($page, $perPage)
                    ->select();
            $users = transform('User', 'details', $users);
            foreach ($users as $k => $v) {
                foreach ($friends['friends'] as $kk => $vv) {
                    if ($vv['faccid'] == $v['user_id']) {
                        $users[$k]['alias'] = $vv['alias']? : '';
                    }
                }
            }
        }

        $pagination = pagination($count, $perPage, $page);
        $this->response($users, $pagination);
    }

    /*
     * 被请求添加好友列表记录
     */

    public function addFriendsLog() {
        $id = $this->user['id'];
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 100);
        $where['faccid'] = $id;

        $where['uf.delete_time'] = 0;
        $userfriend = D('UserFriends');
        $count = $userfriend->table("__USER_FRIENDS__ as uf")->where($where)->count();
        $users = [];
        if ($count >= 0) {
            $users = $userfriend->table("__USER_FRIENDS__ as uf")
                    ->join("__USERS__ as u on uf.accid = u.user_id")
                    ->field('uf.type,uf.msg,u.nickname,uf.accid,u.face')
                    ->where($where)
                    ->order('uf.add_time desc')
                    ->page($page, $perPage)
                    ->select();
            //查出好友关系
            if (C('im.open') == 1) {
                $user['relation'] = 0;
                $imConfig = C('sdk.yxim');
                $yxim = new Yxim($imConfig);
                $result = $yxim->getFriend($this->user['id']);
                if (!empty($result['friends'])) {
                    $faccids = array_column($result['friends'], 'faccid');
                    foreach ($users as $key => $value) {
                        if (in_array($value['accid'], $faccids)) {
                            $users[$key]['state'] = 1; //好友关系，1是，0不是
                        } else {
                            $users[$key]['state'] = 0;
                        }
                    }
                }
            }
        }
        $pagination = pagination($count, $perPage, $page);
        $this->response($users, $pagination);
    }

    private function getImId($id) {
        $imname = C('im.name');
        $sdk = C('sdk');
        $imConfig = $sdk[$imname];
        if ($imname == 'yxim') {
            $yxim = new Yxim($imConfig);
            $result = $yxim->createUserId($id);
            if ($result) {
                D('Users')->setField(['user_id' => $id, 'token' => $result['info']['token']]);
                $user['token'] = $result['info']['token'];
            }
        } else {
            $tcim = new TcIM($imConfig);
            $user['im_sig'] = $tcim->genCmdSig($user['user_id']);
        }
        return $user;
    }

    /*
     * 设置和取消黑名单/静音
     */

    public function setSpecialRelation() {
        $input = $this->request();
        $id = $this->user['id'];
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        $result = $yxim->specializeFriend($id, $input['faccid'], $input['relation_type'], $input['value']);
        if ($result['code'] == 200) {
            $where['accid'] = $id;
            $where['faccid'] = $input['faccid'];
            $value = 0;
            if ($input['value'] == 1) {
                $value = $input['relation_type'];
            }
            $where['delete_time'] = 0;
            D('UserFriends')->where($where)->setField('relation_type', $value);
        }
        $this->createdResponse();
    }

    private function msgbok($uid) {
        $message = D('MessageBox');
        $message->pickGlobalMessage($uid);
        $result = $message->where(['user_id' => $uid, 'is_read' => '0'])->cache(5)->count();
        return $result;
    }

    /*
     * 设置支付密码
     */

    public function setPayPassword() {
        $input = $this->request();
        $this->checkNull($input, ['pay_password']);
        $id = $this->user['id'];
        $data['user_id'] = $id;
        $data['pay_password'] = md5($input['pay_password']);
        if (D('Users')->save($data)) {
            $this->createdResponse(['message' => "设置成功"]);
        }
        $this->createdResponse(['message' => "设置失败"]);
    }

    /*
     * 获取聊吧平台用户,获取手机通讯录功能
     */

    public function getUsers() {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 100);
        $contact = filter($input['contact'], null);
        
        //格式化电话号，去空格和加号，和前面的+86
        
        if (empty($contact)) {
            $this->errorResponse('10002', '通讯录数据为空');
        }
        $contact = str_replace(' ', '', $contact);
        $contact = str_replace('+', '', $contact);
        $contact = str_replace('86', '', $contact);
        $contact = explode(',', $contact);
        $where = ['mobile' => ['in', $contact]];
        $count = D('Users')->where($where)->count();
        $users = [];
        if ($count > 0) {
            $users = D('Users')
                    ->where($where)
                    ->page($page, $perPage)
                    ->select();

            //查出好友关系
            if (C('im.open') == 1) {
                $user['relation'] = 0;
                $imConfig = C('sdk.yxim');
                $yxim = new Yxim($imConfig);
                $result = $yxim->getFriend($this->user['id']);
                if (!empty($result['friends'])) {
                    $faccids = array_column($result['friends'], 'faccid');
                    foreach ($users as $key => $value) {
                        if (in_array($value['user_id'], $faccids)) {
                            $users[$key]['relation'] = 1; //好友关系，1是，0不是
                        } else {
                            $users[$key]['relation'] = 0;
                        }
                    }
                }
            }
        } else {
            $this->errorResponse('10002', '没有通讯录好友');
        }

        $pagination = pagination($count, $perPage, $page);
        $users = transform('User', 'details', $users);
        $this->response($users, $pagination);
    }

    /*
     * 获取群成员信息
     */

    public function getUserinfo() {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 100);
        $uid = explode(',', $input['uid']);
        $users = D('Users')->where(['user_id' => ['in', $uid]])->select();
        $users = transform('User', 'details', $users);
        $this->response($users);
    }

    /*
     * 冻结或解冻帐号
     */

    public function updateState() {
        $input = $this->request();
        $where['state'] = $input['state'];
        $where['user_id'] = $this->user['id'];
        D('Users')->save($where);
        $message = $where['state'] == 1 ? "解冻成功" : "冻结帐号成功";
        $this->response(['code' => 200, 'message' => $message]);
    }

    /*
     * 支付密码检查
     */

    public function checkPayPassword() {
        $input = $this->request();
        $pay_password = $input['pay_password'];
        $uid = $this->user['id'];
        $user = D('Users')->find($uid);
        if (md5($pay_password) == $user['pay_password']) {
            $this->response(['code' => 200, 'message' => '密码一致']);
        }
        $this->errorResponse(400, '密码不一致');
    }

    /*
     * 搜索已添加的好友和群
     */

    public function getFriendAndGroup() {
        $input = $this->request();
        $keyword = $input['keyword'];
        $keyword = "%{$keyword}%";
        $uid = $this->user['id'];

        //从云信获取好友先
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        if ($relation_type == 1) {
            $friends = $yxim->listBlackFriend($this->user['id']);
        } else {
            $friends = $yxim->getFriend($this->user['id']);
        }
        $userM = D('Users');
        $users = [];
        if (!empty($friends['friends'])) {
            $faccids = array_column($friends['friends'], 'faccid');
            $count = $userM->where(['user_id' => ['in', $faccids], 'nickname' => ['like', $keyword], 'closed' => 0])->count();
        }

        if ($count > 0) {
            $users = $userM->where(['user_id' => ['in', $faccids], 'nickname' => ['like', $keyword], 'closed' => 0])->select();
        }
        $users = transform('User', 'details', $users);
        //搜索相关群
        $yxgroupM = D('YxGroup');
        $yxgroup = $yxgroupM->where(['group_name' => ['like', $keyword], 'owner|members' => ['like', $uid]])->select();
        $serach['friends'] = $users;
        $serach['group'] = $yxgroup;

        $this->response($serach);
    }

    /*
     * 举报群或用户
     */

    public function accusation() {
        $input = $this->request();
        if (empty($input['reported'])) {
            $this->errorResponse('10002', '被举报者不能为空');
        }
        $uid = $this->user['id'];
        $data = [
            'content' => $input['content']? : '',
            'reported' => $input['reported'],
            'type' => $input['type'],
            'user_id' => $uid,
            'create_ip' => get_client_ip(),
            'create_time' => time()
        ];
        if (D('Accusation')->create($data)) {
            D('Accusation')->add();
            $this->createdResponse();
        } else {
            $this->errorResponse(401, '提交失败，请重试');
        }
    }

    /**
     * 个人红包记录统计
     */
    public function luckmoneyLog() {
        $uid = $this->user['id'];
        $input = $this->request();

        $type = (int) filter($input['type'], 1); //类型：1收红包，2发红包，
        $time = filter($input['time'], date('Y-m', time())); //类型：1收红包，2发红包，
//        $page = (int) filter($input['page'], 1);
//        $perPage = (int) filter($input['per_page'], 10);
        $where = [];
        $time = getMonthStartAndEndDay($time);
        $start_time = strtotime($time['start_time']);
        $end_time = strtotime($time['end_time']);
        $where['create_time'] = array('between', "{$start_time},{$end_time}");
        $LuckmoneyM = D('Luckmoney');
        if ($type == 1) {
            $where['luck_people'] = $uid;
            $LuckmoneyLogM = D('LuckmoneyLog');
            $count = $LuckmoneyLogM->where($where)->count();
            $LuckmoneyLog = [];
            if ($count > 0) {
                $LuckmoneyLog = $LuckmoneyLogM->where($where)->order('create_time desc')->select();
                ModelUtils::belongsTo($LuckmoneyLog, ['foreignKey' => 'user_id', 'relation' => 'Users', 'refKey' => 'user_id', 'fields' => ['user_id,nickname', 'face'], 'name' => 'user']);
                $LuckmoneyLog = transform('LuckmoneyLog', 'log', $LuckmoneyLog);
            }
            $this->response($LuckmoneyLog);
        } else {
            $where['user_id'] = $uid;
            $count = $LuckmoneyM->where($where)->count();
            $Luckmoney = [];
            if ($count > 0) {
                $Luckmoney = $LuckmoneyM->where($where)->field('type,sort,money,luckmoney_id,create_time')->order('create_time desc')->select();
            }
        }

        $this->response($Luckmoney);
    }

    /*     * 从云信获取用户信息* */

    public function getUserinfoByYx() {
        $uid = $this->user['id'];
        $input = $this->request();
        $accids[] = $input['uid']? : $uid;
        //从云信获取好友先
        $imConfig = C('sdk.yxim');
        $yxim = new Yxim($imConfig);
        $result = $yxim->getUinfos($accids);
        $this->response($result);
    }

}
